package com.smilive.delay.queue.rabbitmq;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: delay_queue_start
 * @Date: 2022-02-09 15:25
 * @Author: smilive
 * @Description:
 */
@Configuration
public class RabbitMqBaseConfig {

    //缓存队列路由key
    public final static String TEMP_ROUTING_KEY  = "temp_key";

    //缓冲队列
    public final static String TEMP_QUEUE = "temp_queue";

    //缓冲交换机
    public final static String TEMP_EXCHANGE = "temp_exchange";

    //死信队列路由key
    public final static String DEAL_ROUTING_KEY  = "deal_key";

    //死信队列
    public final static String DEAL_QUEUE = "deal_queue";

    //死信交换机
    public final static String DEAL_EXCHANGE = "deal_exchange";

    //死信队列 交换机标识符
    public static final String DEAD_LETTER_QUEUE_KEY = "x-dead-letter-exchange";

    //死信队列交换机绑定键标识符
    public static final String DEAD_LETTER_ROUTING_KEY = "x-dead-letter-routing-key";


    //创建缓冲队列
    @Bean
    public Queue tempQueue() {
        // 将普通队列绑定到死信队列交换机上
        Map<String, Object> args = new HashMap<>(2);
        //args.put("x-message-ttl", 5 * 1000);//直接设置 Queue 延迟时间 但如果直接给队列设置过期时间,这种做法不是很灵活
        //这里采用发送消息动态设置延迟时间,这样我们可以灵活控制
        args.put(DEAD_LETTER_QUEUE_KEY, DEAL_EXCHANGE);
        args.put(DEAD_LETTER_ROUTING_KEY, DEAL_ROUTING_KEY);
        return new Queue(TEMP_QUEUE, true, false, false, args);
    }
    //创建缓冲直连交换机
    @Bean
    public DirectExchange tempExchange(){
        return new DirectExchange(TEMP_EXCHANGE);
    }
    //缓冲队列与缓存交换机绑定
    @Bean
    public Binding bindingTempExchange(){
        return BindingBuilder.bind(tempQueue()).to(tempExchange()).with(TEMP_ROUTING_KEY);
    }


    //创建配置死信队列
    @Bean
    public Queue deadQueue() {
        Queue queue = new Queue(DEAL_QUEUE, true);
        return queue;
    }

    //创建死信交换机
    @Bean
    public DirectExchange deadExchange() {
        return new DirectExchange(DEAL_EXCHANGE);
    }

    //死信队列与死信交换机绑定
    @Bean
    public Binding bindingDeadExchange() {
        return BindingBuilder.bind(deadQueue()).to(deadExchange()).with(DEAL_ROUTING_KEY);
    }

}
